﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

public static class ViewModelExtensions
{
    public static IEnumerable<ErrorInfo> GetErrors(this object instance) {
        return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
               from attribute in prop.Attributes.OfType<ValidationAttribute>()
               where !attribute.IsValid(prop.GetValue(instance))
               select new ErrorInfo(prop.Name, attribute.ErrorMessage, instance);
    }

    public class ErrorInfo
    {
        public ErrorInfo(string name, string errorMessage, object instance) {
            Name = name;
            ErrorMessage = ErrorMessage;
            Instance = instance;
        }

        public string Name { get; private set; }
        public string ErrorMessage { get; private set; }
        public object Instance { get; private set; }
    }
}
